<template>
  <el-card class="mt-10">
    <el-form
      label-width="100px"
      class="sku-form"
      ref="skuFormRef"
      :model="skuFormData"
      :rules="skuFormRules"
    >
      <el-form-item label="SPU名称"> {{ spuStore.spuName }} </el-form-item>
      <el-form-item label="SKU名称" prop="skuName">
        <el-input placeholder="请输入SKU名称" v-model="skuFormData.skuName" />
      </el-form-item>
      <el-form-item label="价格(元)" prop="price">
        <el-input-number
          :min="0"
          controls-position="right"
          placeholder="请输入SKU价格"
          class="sku-input-number"
          v-model="skuFormData.price"
        />
      </el-form-item>
      <el-form-item label="重量(千克)" prop="weight">
        <el-input-number
          :min="0"
          controls-position="right"
          placeholder="请输入SKU重量"
          class="sku-input-number"
          v-model="skuFormData.weight"
        />
      </el-form-item>
      <el-form-item label="规格描述" prop="skuDesc">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="请输入SKU规格描述"
          v-model="skuFormData.skuDesc"
        />
      </el-form-item>
      <el-form-item label="平台属性" prop="skuAttrValueList">
        <!-- 响应式布局、栅格布局 -->
        <el-row :gutter="10" class="sku-row">
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            :xl="4.8"
            v-for="(attr, index) in attrList"
            :key="attr.id"
          >
            <div class="sku-select-wrap">
              <span class="sku-select-text">{{ attr.attrName }}</span>
              <!-- 收集数据：必须每个select绑定一个不同的数据 -->
              <el-select
                class="sku-select"
                v-model="skuFormData.skuAttrValueList[index]"
              >
                <el-option
                  v-for="attrValue in attr.attrValueList"
                  :key="attrValue.id"
                  :label="attrValue.valueName"
                  :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row :gutter="10" class="sku-row">
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            :xl="4.8"
            v-for="(saleAttr, index) in spuSaleAttrList"
            :key="saleAttr.id"
          >
            <div class="sku-select-wrap">
              <span class="sku-select-text">{{ saleAttr.saleAttrName }}</span>
              <el-select
                class="sku-select"
                v-model="skuFormData.skuSaleAttrValueList[index]"
              >
                <el-option
                  v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                  :key="saleAttrValue.id"
                  :label="saleAttrValue.saleAttrValueName"
                  :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="图片列表" prop="skuImageList">
        <el-table
          :data="spuImageList"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="60" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <el-image :src="row.imgUrl" class="sku-img" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName" />
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-tag type="success" v-if="row.isDefault === '1'">默认</el-tag>
              <el-button
                type="primary"
                size="small"
                v-else
                @click="setDefaultImg(row)"
              >
                设置默认
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addSku">确定</el-button>
        <el-button @click="showSpuList">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "AddSku",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { getAttrListApi } from "@/api/product/attr";
import { getSpuSaleAttrListApi, getSpuImageListApi } from "@/api/product/spu";
import { saveSkuApi } from "@/api/product/sku";
import { useCategoryStore } from "@/stores/category";
import { useSpuStore } from "@/stores/spu";
import type { AttrList } from "@/api/product/model/attrModel";
import type { SpuSaleAttrList } from "@/api/product/model/spuModel";
import type {
  CommonSku,
  SkuImageList,
  SkuImageItem,
} from "@/api/product/model/skuModel";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

const skuFormRef = ref<FormInstance>();

const skuFormData = reactive<CommonSku>({
  skuName: "",
  price: 0,
  weight: 0,
  skuDesc: "",
  skuAttrValueList: [
    // {
    //   attrId: 0,
    //   attrName: "string",
    //   valueId: 0,
    //   valueName: "string",
    // },
  ],
  skuSaleAttrValueList: [
    // {
    //   saleAttrId: 0,
    //   saleAttrName: "string",
    //   saleAttrValueId: 0,
    //   saleAttrValueName: "string",
    // },
  ],
  skuImageList: [
    // {
    //   id: 0,
    //   imgName: "string",
    //   imgUrl: "string",
    //   isDefault: "string",
    // },
  ],
  skuDefaultImg: "",
});

const skuImageListValidator = (
  rule: any,
  value: SkuImageList,
  callback: any
) => {
  /*
    1. 至少选中一张图片
    2. 选中的图片必须有一个默认图片
  */

  // 1. 至少选中一张图片
  if (!value.length) {
    return callback(new Error("请至少选中一张图片"));
  }

  if (!value.some((img) => img.isDefault === "1")) {
    return callback(new Error("选中的图片必须有一个默认图片"));
  }

  callback();
};

const skuFormRules = reactive<FormRules>({
  skuName: [{ required: true, message: "请输入SKU名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入SKU价格", trigger: "blur" }],
  weight: [{ required: true, message: "请输入SKU重量", trigger: "blur" }],
  skuDesc: [{ required: true, message: "请输入SKU描述", trigger: "blur" }],
  skuAttrValueList: [{ required: true, message: "请选择平台属性" }],
  skuSaleAttrValueList: [{ required: true, message: "请选择销售属性" }],
  skuImageList: [{ required: true, validator: skuImageListValidator }],
});

// 选择复选框触发事件
const handleSelectionChange = (val: SkuImageList) => {
  // val就是选中的值
  skuFormData.skuImageList = val;
};

// 设置默认图片
const setDefaultImg = (row: SkuImageItem) => {
  spuImageList.value.forEach((img) => (img.isDefault = "0"));
  row.isDefault = "1";
  skuFormData.skuDefaultImg = row.imgUrl;
  // 设置默认的图片必须是选中的才清空校验结果
  if (skuFormData.skuImageList.some((img) => img === row)) {
    skuFormRef.value?.clearValidate(["skuImageList"]);
  }
};

const emit = defineEmits(["setIsShow"]);

const showSpuList = () => {
  emit("setIsShow", 1);
};

const addSku = async () => {
  await skuFormRef.value?.validate();
  saveSkuApi({
    ...skuFormData,
    skuAttrValueList: skuFormData.skuAttrValueList
      .filter(Boolean)
      .map((attr) => {
        const [attrId, attrName, valueId, valueName] = (attr as string).split(
          ":"
        );
        return {
          valueId: +valueId,
          valueName: valueName,
          attrId: +attrId,
          attrName: attrName,
        };
      }),
    skuSaleAttrValueList: skuFormData.skuSaleAttrValueList
      .filter(Boolean)
      .map((saleAttr) => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = (
          saleAttr as string
        ).split(":");
        return {
          saleAttrId: +saleAttrId,
          saleAttrName: saleAttrName,
          saleAttrValueId: +saleAttrValueId,
          saleAttrValueName: saleAttrValueName,
        };
      }),
    spuId: spuStore.id as number,
    category3Id: categoryStore.category3Id as number,
  });

  ElMessage.success("添加SKU成功");

  showSpuList();
};

const attrList = ref<AttrList>([]);
const spuSaleAttrList = ref<SpuSaleAttrList>([]);
const spuImageList = ref<SkuImageList>([]);

const categoryStore = useCategoryStore();
onMounted(async () => {
  const { category1Id, category2Id, category3Id } = categoryStore;
  attrList.value = await getAttrListApi({
    category1Id: category1Id as number,
    category2Id: category2Id as number,
    category3Id: category3Id as number,
  });
});

const spuStore = useSpuStore();
onMounted(async () => {
  spuSaleAttrList.value = await getSpuSaleAttrListApi(spuStore.id as number);
});
onMounted(async () => {
  const res = await getSpuImageListApi(spuStore.id as number);
  spuImageList.value = res.map((img) => {
    return {
      ...img,
      isDefault: "0",
    };
  });
});
</script>

<style scoped>
.sku-input-number,
.sku-row {
  width: 100%;
}

.sku-select-wrap {
  display: flex;
}
.sku-select-text {
  width: 100px;
  text-align: right;
}
.sku-select {
  margin-left: 10px;
  margin-bottom: 10px;
  flex: 1;
}

.sku-form :deep(.el-input__inner) {
  text-align: left;
}

.sku-img {
  width: 100px;
  height: 100px;
}
</style>
